import os
from pathlib import Path
import zipfile
from zipfile import ZipFile
import uuid
import shutil

# 解压文件
from configs import logger


class ZipFileHand(object):
    '''
    处理传过来的压缩文件
    '''

    def __init__(self, path, out_dir=None):
        '''
        :param path:  文件路径
        :param out_dir:  输出路径
        '''
        # 文件所在路径
        self.path = path
        # 文件名称
        self.name = os.path.basename(path)
        # 解压路径

        base_out_path = os.path.dirname(path)
        self.out_path = os.path.join(base_out_path, str(uuid.uuid1()))
        if out_dir is None:
            os.mkdir(self.out_path)
            self.out_dir = self.out_path
        else:
            self.out_dir = out_dir
        self.msg = ''

    def hand_zip_file(self):
        '''
        判断文件是否是压缩文件
        :return:
        '''
        if self.name and self.name.upper().endswith('ZIP'):
            # 说明是zip文件
            self.extract_zip(self.path, self.out_dir)
        if self.name and (self.name.upper().endswith('RAR') or self.name.upper().endswith('RAR.GZ')):
            # 说明是rar文件
            self.extrat_rar(self.path, self.out_dir)

    def extrat_rar(self, zip_name, out_dir):
        try:

            '''
            解压rar文件
            :param zip_name:  压缩文件全路径
            :param out_dir:  输出文件的文件夹
            :return:
            '''
            # z = rarfile.RarFile(zip_name)
            # z.extractall(out_dir)
            # z.close()
        except:
            self.msg = 'rar文件解压失败'

    # 解压zip文件文件
    def extract_zip(self, zip_name, out_dir):
        '''
        解压zip文件
        :param zip_name: 压缩文件全路径
        :param out_dir: 输出文件的文件夹
        :return:
        '''
        '''将 zip_name 文件解压到 out_dir 目录
        '''
        try:
            out_dir = Path(out_dir)
            with ZipFile(zip_name, allowZip64=True) as Z:
                # 排除目录文件
                file_iter = (file for file in Z.filelist if not file.is_dir())
                for file in file_iter:
                    # 编码文件名称为 utf 格式
                    file.filename = self.decode_path(file.filename)
                    Z.extract(file, out_dir)
        except Exception as e:
            logger.exception(e)
            self.msg = 'zip文件解压失败'

    def decode_path(self, path):
        '''将乱码的路径编码为 UTF8
            :path: Path 的实例
            '''
        try:
            path_name = path.decode('utf-8')
        except:
            try:
                path_name = path.encode('437').decode('gbk')
                path_name = path_name.encode('utf-8').decode('utf-8')
            except:
                path_name = path
        logger.debug("当前文件名为:{}", path_name)
        return path_name


def zip_file(paths=None, result_name=None):
    if paths:
        zf = ZipFile(result_name, mode="w")
        for item in paths:
            zf.write(item, arcname=os.path.basename(item), compress_type=zipfile.ZIP_DEFLATED)
        zf.close()


img_puf = ['jpg', 'png', 'webp', 'gif', 'bmp', 'tif', 'gif']


def readFile(path, out_dir):
    for one_file in os.listdir(path):
        one_path = os.path.join(path, one_file)
        if os.path.isdir(one_path):
            readFile(one_path, out_dir)
        else:
            # if one_path.endswith('zip') or one_path.endswith('ZIP'):
            #     # zipHand = ZipFileHand(one_path, out_dir)
            #     # zipHand.hand_zip_file()
            #     print('zipfile',one_path)
            # else:
            try:
                sufxx = os.path.basename(one_path).rsplit('.')
                if sufxx[1].lower() in img_puf:
                    shutil.copy(one_path, out_dir)
            except:
                print('该文件已经存在')


if __name__ == '__main__':
    # out_dir = 'D:\\mywork\\imgs\\2'
    source_dir = r'D:\mywork\imgs\555'
    # out_dir = 'D:\mywork\imgs\dataset\data2'
    # readFile(source_dir, out_dir)
    # print('compelete')
    # # readFile(source_dir, out_dir)
    # # # tempfilename = 'D:\\gitwork\\self\\imghand\\service\\temp\\ditui\\20230726174351_884.xlsx'
    # # # zip_path = 'D:\\gitwork\\self\\imghand\\service\\temp\\ditui\\20230726174351_884.zip'
    # # # zip_file(paths=[tempfilename],result_name=zip_path)
    zipHand = ZipFileHand(os.path.join(source_dir, 'test.zip'), out_dir=os.path.join(source_dir, 'result'))
    zipHand.hand_zip_file()
    logger.debug('解压成功:{}', zipHand.out_dir)
